package com.ruixin.base.proxy;

import com.ruixin.base.exception.BaseException;
import com.ruixin.base.factory.Factory;
import com.ruixin.base.util.BeanUtil;
import net.sf.cglib.proxy.Enhancer;

import java.lang.reflect.Constructor;

/**
 * 代理帮助类
 */
public class ProxyHelper {

    //存储代理对象类和原始类的关系
    private static Factory<Class<?>,Class<?>> proxyClasses = new Factory<>();

    public static Factory<Class<?>, Class<?>> getProxyClasses() {
        return proxyClasses;
    }

    public static void setProxyClasses(Factory<Class<?>, Class<?>> proxyClasses) {
        ProxyHelper.proxyClasses = proxyClasses;
    }

    /**
     * 获取代理对象
     * @param clz
     * @param args
     * @param <T>
     * @return
     * @throws BaseException
     */
    public static <T> T newProxyInstance(Class<T> clz,Object ... args) throws BaseException {
        BaseInterceptor baseInterceptor = new BaseInterceptor();
        Enhancer enhancer = baseInterceptor.createEnhancer(clz);
        T result = null;
        if(args.length==0){
            result = clz.cast(enhancer.create());
        }else{
            Constructor<?> constructor = BeanUtil.getConstructor(clz, args);
            result = clz.cast(enhancer.create(constructor.getParameterTypes(),args));
        }
        proxyClasses.put(result.getClass(),clz);
        return result;
    }

    /**
     * 判断当前类是不是代理类
     * @param clz
     * @return
     */
    public static boolean isProxy(Class<?> clz){
        return proxyClasses.containsKey(clz);
    }

    /**
     * 通过代理类获取原始类，如果非代理类，则返回原值
     * @param clz
     * @return
     */
    public static Class<?> getOriginalClass(Class<?> clz){
        return proxyClasses.getOrDefault(clz,clz);
    }

}
